<?php

namespace App\Server\API;

use App\Model\API\UserModel;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class LoginService
{
    /**
     * 登录方法
     */
    public static function Login($data)
    {
        //数据验证
        $rules = config('rules.login');
        $message = config('errorMessages.login');
        $validator = Validator::make($data,$rules,$message);
        foreach ($validator->errors()->all() as $v) {
            if (!empty($v)) {
                $code = config('errorCodes.login.code');
                self::return_response($code,$v);
            }
        }
        //查询用户账号是否存在
        $user_info = UserModel::selectUserByName($data['username']);
        if (empty($user_info)) {
            responseJson(config('errorCodes.userNotExists'));
        }
        //验证账户是否激活
        self::checkStatus($user_info->status);
        //验证密码
        $password = md5($data['password'] . $user_info->rand);
        if ($user_info->password !== $password) {
            responseJson(config('errorCodes.passwordError'));
        }
        //更新token
        $user_info->token = self::updateToken($user_info->id);
        unset($user_info->password);
        unset($user_info->rand);
        //返回用户数据
        responseJson('200','登录成功',$user_info);

    }
    /**
     * 生成token/更新token
     */
    private static function updateToken($id)
    {
        $token = md5(uniqid());
        $result = UserModel::updateTokenById($id,$token);
        if (!$result) {
            responseJson(config('errorCodes.tokenUpdateError.code'),'登录失败，请重试');
        }
        return $token;
    }
    /**
     * 返回响应的方法
     */
    public static function return_response($code,$message)
    {
        echo json_encode(['code'=>$code,'msg'=>$message],JSON_UNESCAPED_UNICODE);die;
    }
    /**
     * 验证账号是否激活
     */
    public static function checkStatus($status) {
        switch ($status) {
            case 1:
                responseJson(config(errorCodes.userStatus.code),'用户未激活，请前往邮箱激活');
                break;
            case 3:
                responseJson(config(errorCodes.userStatus.code),'该账号已冻结');
                break;
            case 4:
                responseJson(config(errorCodes.userStatus.code),'该账号已删除');
                break;
        }
    }
}

